import axios from 'axios'
import { Toast } from 'vant'
import { getToken } from './local'

// 1.创建axios实例
const request = axios.create({
  baseURL: 'http://interview-api-t.itheima.net/h5/',
  timeout: 5000
})

// 2.请求拦截
request.interceptors.request.use((config) => {
  const token = getToken()
  if (token) {
    config.headers = {
      Authorization: `Bearer ${token}`
    }
  }
  return config
}, (err) => {
  return Promise.reject(err)
})

// 3.响应拦截
request.interceptors.response.use((res) => {
  return res.data
}, (err) => {
  if (err.response.data) {
    Toast(err.response.data.message)
  }
  return Promise.reject(err)
})

// 导出axios实例
export default request
